package listbyorder.access001_100.test16;

import java.util.Arrays;

/**
 * 双指针求解
 *
 * @author code_yc
 * @version 1.0
 * @date 2020/5/28 9:29
 */
public class Solution2 {

    public int threeSumClosest(int[] nums, int target) {
        if (nums == null || nums.length < 3) return 0;
        int sum = Integer.MAX_VALUE;
        int ans = 0;
        Arrays.sort(nums);
        for (int i = 0; i < nums.length - 2; i++) {
            int left = i + 1;
            int right = nums.length - 1;
            while (left < right) {
                if (Math.abs(nums[i] + nums[left] + nums[right] - target) < sum) {
                    ans = nums[i] + nums[left] + nums[right];
                    sum = Math.abs(ans - target);
                }
                if (nums[left] + nums[right] < target - nums[i]) {
                    left++;
                } else {
                    right--;
                }
            }
        }
        return ans;
    }
}
